<template>
    <div class="container_box">
        <el-scrollbar ref="scrollbarRef" class="main_box2">
            <div class="wrapper">
                <el-card v-if="activeTitle" shadow="never" class="card_title">
                    <span>{{ activeTitle }}</span>
                </el-card>
                <el-card class="header" shadow="never">
                    <Step
                        ref="stepRef"
                        :current-step="currentStep"
                        :steps-label="stepsLabel"
                        :total-steps="stepsLabel.length" />
                </el-card>
                <el-card class="centent_box" shadow="never">
                    <div class="centent_top">
                        <div class="left">
                            <div v-show="currentStep == 1">
                                <One ref="OneRef" :page-type="pageType" :group_id="group_id" @submit="onChildValid" />
                            </div>
                            <div v-show="currentStep == 3">
                                <Two ref="TwoRef" :page-type="pageType" @submit="onChildValid" />
                            </div>
                            <div v-show="currentStep == 2">
                                <Three
                                    ref="ThreeRef"
                                    :page-type="pageType"
                                    :basic-date="basicDate"
                                    @submit="onChildValid" />
                            </div>
                        </div>
                        <div v-show="currentStep < 4" class="right">
                            <ActivityPhone />
                            <!-- <Phone /> -->
                        </div>
                    </div>
                    <div v-show="currentStep == 4">
                        <Four ref="FourRef" :page-type="pageType" @submit="onChildValid" />
                    </div>
                    <div v-show="currentStep == 5"><Five ref="FiveRef" :page-type="pageType" @submit="onSubmit" /></div>
                </el-card>
            </div>
        </el-scrollbar>
        <div class="footer_box">
            <el-button v-if="currentStep == 1" @click="onRouter()">取消</el-button>
            <el-button v-else @click="onStep">上一步</el-button>
            <el-button v-if="currentStep != 5" type="primary" @click="onNext(currentStep)">下一步</el-button>
            <template v-else>
                <el-button v-if="pageType == 'look'" type="primary" @click="onRouter()">返回</el-button>
                <el-button v-else type="primary" @click="onNext(currentStep)">保存</el-button>
            </template>
        </div>
    </div>
</template>

<script setup lang="ts">
import Step from '@/components/Step.vue';
import One from './components/One.vue';
import Two from './components/Two.vue';
import Three from './components/Three.vue';
import Four from './components/Four.vue';
import Five from './components/Welcome.vue';
import ActivityPhone from '@/components/zw/phonePreview1.0/activityPhonePreview/fissionDrainage/index.vue';
import { fissionCreate, fissionLook, fissionEdit } from '@/api/smartMarketing/fissionDrainage';
import { ref, onMounted, provide, computed, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useStore } from '@/store';
import bus from '@/utils/bus';

const store = useStore();
const router = useRouter();
const route = useRoute();
const scrollbarRef = ref<any>(null);
const stepRef = ref<any>();
const pageType = route.query.type;
const OneRef = ref<any>();
const TwoRef = ref<any>();
const ThreeRef = ref<any>();
const FourRef = ref<any>();
const FiveRef = ref<any>();
const currentStep = ref(1);
const create_type = ref(route.query?.create_type);
const activeTitle = ref(route.query?.title);
const group_id = ref(Number(route.query?.group_id));
provide('create_type', create_type);

/** 是否禁用 */
const formDisabled = ref(false);
provide('formDisabled', formDisabled);

const basicDate = computed(() => OneRef.value?.formData);

const stepsLabel: any = ref([
    { title: '基础设置', stepIndex: 1 },
    { title: '活动规则及奖品', stepIndex: 2 },
    { title: '高级设置', stepIndex: 3 },
    { title: '海报设置', stepIndex: 4 },
    { title: '欢迎语设置', stepIndex: 5 }
]);
/**
 * @description: 滚动到顶部
 */
const setScrollTopHandle = () => {
    nextTick(() => {
        scrollbarRef.value?.setScrollTop(0);
    });
};
const onStep = () => {
    currentStep.value--;
    stepRef.value.back();
};
const onChildValid = () => {
    currentStep.value++;
    stepRef.value.next();
    setScrollTopHandle();
};
const onRouter = () => {
    store.dispatch('setGroupId', OneRef.value.formData.group_id);
    router.back();
};
const findMax = (data: any) => {
    const res = data.reduce((preVal: any, curVal: any) => {
        return preVal.help_num > curVal.help_num ? preVal.help_num : curVal.help_num;
    });
    return data.length == 1 ? data[0].help_num : res;
};
const onNext = (step: number) => {
    if (pageType == 'look') {
        currentStep.value == 5 && onRouter();
        currentStep.value++;
        stepRef.value.next();
        return;
    }
    switch (step) {
        case 1:
            OneRef.value.onSubmit();
            ThreeRef.value.setFirstDefaultTime();
            break;
        case 3:
            TwoRef.value.onSubmit();
            break;
        case 2:
            bus.emit('getPrize', ThreeRef.value.formData.reward_list);
            TwoRef.value.maxAssitNum = findMax(ThreeRef.value.formData.reward_list);
            ThreeRef.value.onSubmit();
            break;
        case 4:
            FourRef.value.onSubmit();
            break;
        case 5:
            FiveRef.value.onSubmit();
            break;
    }
};

const onSubmit = () => {
    // 处理参与活动提示语
    let dom: HTMLDivElement | null = document.createElement('div');
    dom.innerHTML = FourRef.value.formData.activity_clues;

    // 处理奖品类型的入参 ==> 切换时为了保留数据
    const reward = ThreeRef.value.formData.reward_list;
    const paramsReward = reward.map((v: any, index: number) => {
        v.step = index + 1;
        const item: any = {};
        if (v.reward_type == 1) {
            item.red_envelope_type = 1;
            item.red_envelope_num = 0; // 个数
            item.red_envelope_money = 0; //  金额
            item.red_envelope_range = 0; //  金额
            item.red_envelope_total = 0; //  总金额
        } else {
            item.reward_desc = ''; // 描述
            item.reward_stock = 1; // 库存
            item.red_envelope_total = +v.red_envelope_total;
        }
        return { ...v, ...item };
    });
    if (!TwoRef.value.formData.isHight) {
        TwoRef.value.formData.tag = [];
    }

    FourRef.value.formData.poster.position = (FourRef.value.getPostersInfo() ?? {}).position;

    const params = {
        ...OneRef.value.formData,
        ...TwoRef.value.formData,
        ...ThreeRef.value.formData,
        ...FourRef.value.formData,
        employee_ids: TwoRef.value.employeeList.map((v: any) => v.id),
        welcome_info: FiveRef.value.formData.welcome_info,
        welcome_type: FiveRef.value.formData.welcome.type,
        welcome_content: FiveRef.value.formData.welcome.content,
        welcome_attachment: FiveRef.value.formData.welcome.attachment,
        local_link: FiveRef.value.formData.welcome.local_link,
        local_content: FiveRef.value.formData.welcome.local_content,
        // 分时段欢迎语开关
        time_welcome_switch: 2,
        time_welcome: [],
        link_img: FiveRef.value.formData.link_img,
        link_title: FiveRef.value.formData.link_title,
        link_desc: FiveRef.value.formData.link_desc,
        // 活动类型 1-企微 2-企微+公众号
        type: create_type.value || 1,
        activity_clues: dom.innerText,
        reward_list: paramsReward,
        end_tag: TwoRef.value.formData.end_tag.map((item: any) => item.id)
    };
    if (pageType == 'edit') {
        fissionEdit({ activity_id: route.query.id, ...params }).then(() => {
            ElMessage.success('编辑成功');
            router.push({
                path: '/smartMarketing/fission/fissionDrainage',
                query: { group_id: OneRef.value.formData.group_id }
            });
        });
    } else {
        fissionCreate(params).then(() => {
            ElMessage.success('新建成功');
            router.push({
                path: '/smartMarketing/fission/fissionDrainage',
                query: { group_id: OneRef.value.formData.group_id }
            });
        });
    }
    dom = null;
    return;
};
const onLook = async () => {
    const res = await fissionLook({ activity_id: route.query.id });

    // 如果是活动状态是进行中，已结束，提前结束。则禁用一些内容
    // 活动状态 1:未开始 2:进行中 3:已结束 4:提前结束
    if (res.activity_status !== 1) {
        formDisabled.value = true;
        // 结束时间给空
        if (res.period_type === 1) {
            res.effect_time = [res.created_at, ''];
        }
    }
    create_type.value = res.type;
    //  基础设置
    OneRef.value.formData.official_account_id = res.official_account_id;
    OneRef.value.formData.activity_name = res.activity_name;
    OneRef.value.formData.group_id = res.group_id;
    OneRef.value.formData.period_type = res.period_type;
    OneRef.value.formData.effect_date = res.effect_time;
    OneRef.value.formData.created_at = res.created_at;
    //  高级设置
    TwoRef.value.formData.employee_ids = res.employee_ids?.map((item: any) => item.id);
    TwoRef.value.employeeList = res.employee_ids;
    TwoRef.value.formData.employee_setting = res.employee_setting;
    TwoRef.value.formData.participate_tag = res.participate_tag?.map((item: any) => item.id);
    TwoRef.value.AllTags = res.participate_tag;
    TwoRef.value.formData.help_tag = res.help_tag?.map((item: any) => item.id);
    TwoRef.value.helpTags = res.help_tag;
    TwoRef.value.formData.winner_tag = res.winner_tag?.map((item: any) => item.id);
    TwoRef.value.rewardTags = res.winner_tag;
    TwoRef.value.formData.receive_tag = res.receive_tag?.map((item: any) => item.id);
    TwoRef.value.receiveTags = res.receive_tag;
    TwoRef.value.formData.flow_restrict = res.flow_restrict;
    TwoRef.value.formData.flow_second = res.flow_second;
    TwoRef.value.formData.flow_assist_num = res.flow_assist_num;
    TwoRef.value.formData.end_tag = res.end_tag;
    TwoRef.value.isRenderAddEndTagButton = !res.end_tag.length;
    if (res.tag?.length > 0 || res.prize_tags?.length > 0 || res.end_tag.length > 0) {
        TwoRef.value.formData.isHight = true;
    }
    if (res.tag) {
        TwoRef.value.getLook(res.tag, 1);
    }
    if (res.prize_tags) {
        TwoRef.value.getLook(res.prize_tags, 2);
    }
    // 活动规则及奖品
    ThreeRef.value.formData.reward_type = res.reward_type;
    ThreeRef.value.formData.reward_list = [];
    ThreeRef.value.formData.reward_end_switch = res.reward_end_switch;
    nextTick(() => {
        ThreeRef.value.formData.reward_list = res.reward_list;
        ThreeRef.value.setDefaultAwardList();
    });

    ThreeRef.value.formData.customer_type = res.customer_type;
    ThreeRef.value.formData.customer_gender = res.customer_gender;
    ThreeRef.value.formData.help_effect = res.help_effect;
    // 海报设置
    FourRef.value.formData.code = res.poster_type == 2 ? res.poster_id : res.code;
    FourRef.value.formData.poster = res.poster;
    if (res.poster.poster_type == 1) {
        FourRef.value.formData.poster.poster_absolute_url = res.poster.absolute_url;
    } else if (res.poster.poster_type == 2) {
        FourRef.value.formData.poster.local_absolute_url = res.poster.absolute_url;
    }
    FourRef.value.setPosition(res.poster.position);
    FourRef.value.formData.keywords = res.keywords;
    res.activity_clues = res.activity_clues
        .replace(/\n/g, `<br />`)
        .replaceAll(`【${res.keywords}】`, `<span class="key_tag" contenteditable="false">【${res.keywords}】</span>`);
    FourRef.value.formData.activity_clues = res.activity_clues;
    FourRef.value.formData.activity_rule_desc = res.activity_rule_desc;

    // 欢迎语设置
    // FiveRef.value.formData.welcome_attachment = res.welcome_attachment?.map(item=>({type:item.type,media_content_id:item.content_id}))

    Object.assign(FiveRef.value.formData, {
        welcome: {
            type: res.welcome_type,
            content: res.welcome_content,
            attachment: [],
            local_link: [],
            local_content: []
        },
        time_welcome_flag: 2,
        time_welcome: [{ content: '', week: [] }],
        link_img: res.activity_image,
        link_title: res.title,
        link_desc: res.desc,
        tag_list: []
    });
    FiveRef.value.onLookData(res);
};
// 查看活动
onMounted(() => {
    route.query.type && onLook();
});
</script>

<style scoped lang="scss">
.wrapper {
    .card_title {
        font-size: 16px;
        font-weight: 500;
        border-bottom: none;
    }

    .header {
        margin-bottom: 20px;
        border-top: none;
    }

    .centent_box {
        border-bottom: none;

        .centent_top {
            // display: grid;
            // grid-template-columns: 1.6fr 1fr;
            display: flex;

            .left {
                flex: 1;
            }

            .right {
                // height: 520px;
                display: flex;
                justify-content: center;
                padding: 0 48px;
                margin-bottom: 20px;

                // transform: scale(0.5);
            }
        }

        .footer {
            padding-top: 20px;
            text-align: center;
            border-top: 1px solid #d9d9d9;
        }
    }
}

// 此处是为了解决页面铺天盖地没加scoped带来的影响。在当前页面直接覆盖style.
// 可以搜索样式el-dialog__header查看未加scoped的地方
:deep(.el-dialog.dialog_body_noPadding) {
    .el-dialog__header {
        margin: 0;
        padding: 16px;
        border-bottom: 1px solid #eaeaea;

        .el-dialog__headerbtn {
            top: 0;
        }
    }
}
</style>
